package com.info.zhiduoduo.admin.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.info.zhiduoduo.admin.listener.UploadDealProjectListener;
import com.info.zhiduoduo.admin.model.formbean.crowdsource.UploadProjectFileUrlFormBean;
import com.info.zhiduoduo.admin.model.formbean.project.*;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.KingdeeTemplateConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
import com.info.zhiduoduo.common.constants.company.CompanyPayType;
import com.info.zhiduoduo.common.constants.invoice.InvoiceType;
import com.info.zhiduoduo.common.constants.pay.PayTypeSn;
import com.info.zhiduoduo.common.constants.pay.PinganPayOrderState;
import com.info.zhiduoduo.common.constants.pay.ZhaoShangPayOrderState;
import com.info.zhiduoduo.common.constants.project.CalcAmountType;
import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.RollbackException;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.*;
import com.info.zhiduoduo.core.dto.pingan.BatchTransferQuery;
import com.info.zhiduoduo.core.dto.pingan.PinganTransferQueryFormBean;
import com.info.zhiduoduo.core.dto.pingan.SingleTransferQuery;
import com.info.zhiduoduo.core.dto.zhaoshang.ZhaoShangOutlineDTO;
import com.info.zhiduoduo.core.dto.zhaoshang.ZhaoShangPayDetailedDTO;
import com.info.zhiduoduo.core.dto.zhaoshang.ZhaoShangQueryPayDetailedFormBean;
import com.info.zhiduoduo.core.dto.zhaoshang.ZhaoShangTransactionOutlineFormBean;
import com.info.zhiduoduo.core.formbean.ProjectCheckFormBean;
import com.info.zhiduoduo.core.service.*;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.common.DocService;
import com.info.zhiduoduo.core.service.payment.thirdpay.*;
import com.info.zhiduoduo.repository.dto.crowdsource.ExportProjectAcceptanceDto;
import com.info.zhiduoduo.repository.dto.maker.StudioDetailDto;
import com.info.zhiduoduo.repository.dto.partner.PartnerProjectBrokerageDto;
import com.info.zhiduoduo.repository.dto.project.*;
import com.info.zhiduoduo.repository.entity.company.CompanyAccountflow;
import com.info.zhiduoduo.repository.entity.company.CompanyPayment;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceTradeRecord;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceTradeRecordItem;
import com.info.zhiduoduo.repository.entity.invoice.Invoice;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.entity.partner.PartnerBrokerage;
import com.info.zhiduoduo.repository.entity.pay.Payment;
import com.info.zhiduoduo.repository.entity.system.SystemManager;
import com.info.zhiduoduo.repository.mapper.company.*;
import com.info.zhiduoduo.repository.mapper.invoice.InvoiceMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerBankcardMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.order.TradeRecordMapper;
import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class ProjectService extends BaseService {

	@Resource
	CompanyProjectMapper projectMapper;
	@Resource
	PartnerBrokerageMapper partnerBrokerageMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	TradeRecordMapper tradeRecordMapper;
	@Resource
	InvoiceMapper invoiceMapper;
	@Resource
	MakerBankcardMapper makerBankcardMapper;
	@Resource
	CompanyAccountMapper companyAccountMapper;
	@Resource
	CompanyPaymentMapper companyPaymentMapper;
	@Resource
	CompanyMapper companyMapper;

	@Autowired
	MakerService makerService;
	@Autowired
	WxMessageService wxMessageService;
	@Autowired
	CoreProjectService coreProjectService;
	@Autowired
	ZhiduoduoProjectService zhiduoduoProjectService;
	@Autowired
	CrowdsourceProjectService crowdsourceProjectService;
	@Autowired
	ZhaoShangPayService zhaoShangPayService;
	@Autowired
	PinganPayService pinganPayService;
	@Autowired
	AliPayService aliPayTransferService;
	@Autowired
	CoreBrokerageService coreBrokerageService;
	@Autowired
	CoreCompanyService coreCompanyService;
	@Autowired
	CoreInvoiceService coreInvoiceService;
	@Autowired
	DocService docService;

	@Autowired
	PayConfig payConfig;
	@Autowired
	ZddUrlConfig zddUrlConfig;
	@Autowired
	CommonConfig commonConfig;
	@Resource
	KingdeeTemplateConfig kingdeeTemplateConfig;

	@Resource
	CompanyRechargeMapper companyRechargeMapper;

	/**
	 * 获取项目列表
	 */
	public SmartResult<ProjectBriefDto> getProjectList(BaseSimpleFormBean<ProjectListFormBean> formBean) {
		//获取地址
		SystemManager systemManager = new SystemManager().selectOne(Condition.create().eq("managerid",  formBean.getUserid()));
		if (systemManager == null) return optFailSmartResult();
		String dockingCity = systemManager.getDockingCity();



		ProjectListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		int state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int categoryid = reqdata.getCategoryid();
		Date projectStartDate = reqdata.getProjectStartDate();
		Date projectEndDate = reqdata.getProjectEndDate();

		int whetherUploadFile = reqdata.getWhetherUploadFile();
		String strUploadFile = "";
		//1 已上传证据链  2  未上传证据链
		if (1 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url != '' and cp.attachment_url is not null) or cp.delivery_path is not null) ";
		} else if (2 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url is null or cp.attachment_url = '') and cp.delivery_path is null) ";
		}
		int whetherSupplement = reqdata.getWhetherSupplement();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<ProjectBriefDto> list = projectMapper.getProjectBriefList(name, categoryid, state, startDate, endDate, strUploadFile,
				whetherSupplement, projectStartDate, projectEndDate,dockingCity,reqdata.getWhetherThereIsARefund());

		//项目剩余天数
		Date now = new Date();
		list.forEach(p -> {
			int projectcycle = p.getProjectcycle();
			if (p.getProjectstart() != null && p.getState() != CompanyProjectState.COMPLETED) {
				int leftDays = projectcycle - DateUtil.getIntervalDays(p.getProjectstart(), now);
				p.setLeftDays(leftDays);
			}

			//项目支付状态
			TradeRecord tradeRecord = zhiduoduoProjectService.getCompanyPayUserAmountTradeRecord(p.getProjectid());
			if (tradeRecord != null) {
				p.setTradeid(tradeRecord.getTradeid()).setTradestate(tradeRecord.getTradestate()).setRepay(tradeRecord.getRepay());
			}

		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	/**
	 * 获取九歌线下支付项目列表
	 */
	public SmartResult<ProjectJiugeOfflinePayDto> getJiugeOfflinePayProjectList(
			BaseSimpleFormBean<JiugeOfflinePayProjectListFormBean> formBean) {

		JiugeOfflinePayProjectListFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String name = reqdata.getName();
		int state = NumberUtil.safeInt(reqdata.getState());
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date((0));
		if (endDate == null) endDate = new Date();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<ProjectJiugeOfflinePayDto> list = projectMapper.getJiugeOfflinePayProjectList(name, state, startDate, endDate);

		//项目剩余天数
		Date now = new Date();
		list.forEach(p -> {
			int projectcycle = p.getProjectcycle();
			if (p.getProjectstart() != null && p.getState() != CompanyProjectState.COMPLETED) {
				int leftDays = projectcycle - DateUtil.getIntervalDays(p.getProjectstart(), now);
				p.setLeftDays(leftDays);
			}
			StudioDetailDto userInfo = makerStudioMapper.getStudioDetail(p.getUserid());
			// 创客银行卡信息
			p.setUserAcctname(userInfo.getRealname())
					.setUserAcctno(userInfo.getAcctno())
					.setUserBankname(userInfo.getBankname())
					.setOpenAcctBankName(userInfo.getOpenAcctBankName())
					.setUserAcctname2(userInfo.getPayername2())
						.setUserAcctno2(userInfo.getAcctno2())
						.setUserBankname2(userInfo.getBankname2())
						.setOpenAcctBankName2(userInfo.getOpenAcctBankName2())
						.setBankno2(userInfo.getBankno2());
		});
		return smartResult(list, page.getTotal(), page.getPages(), page.getPageNum());
	}

	public void downloadJiugeOfflinePayProjectList(HttpServletResponse response, JiugeOfflinePayProjectListFormBean reqdata) {
		if (reqdata == null) {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		String name = reqdata.getName();
		int state = NumberUtil.safeInt(reqdata.getState());
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();

		if (startDate == null) startDate = new Date((0));
		if (endDate == null) endDate = new Date();

		List<ProjectJiugeOfflinePayDto> list = projectMapper.getJiugeOfflinePayProjectList(name, state, startDate, endDate);

		list.forEach(p -> {
			StudioDetailDto userInfo = makerStudioMapper.getStudioDetail(p.getUserid());
			// 创客银行卡信息
			p.setUserAcctname(userInfo.getRealname())
					.setUserBankname(userInfo.getBankname())
					.setUserAcctno(userInfo.getAcctno())
					.setOpenAcctBankName(userInfo.getOpenAcctBankName());
			if (p.getInvoicetype() == InvoiceType.SPECIAL) {
				p.setUserAcctname2(userInfo.getPayername2())
						.setUserAcctno2(userInfo.getAcctno2())
						.setUserBankname2(userInfo.getBankname2())
						.setOpenAcctBankName2(userInfo.getOpenAcctBankName2())
						.setBankno2(userInfo.getBankno2());
			}
		});

		EasyExcelUtil.download(response, "线下支付项目列表", ProjectJiugeOfflinePayDto.class, list);
	}

	/**
	 * 获取项目详情
	 */
	public SmartResult<ProjectDto> getProjectDetail(BaseSimpleFormBean<Integer> formBean) {

		Integer projectid = formBean.getReqdata();
		if (projectid == null || projectid <= 0) return errorParamSmartResult();

		return smartResult(zhiduoduoProjectService.getProjectDetail(projectid));
	}

	/**
	 * 编辑项目
	 */
	public SmartResult editProject(BaseSimpleFormBean<EditProjectFormBean> formBean) {
		EditProjectFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		int projectid = reqdata.getProjectid();
		String projectname = reqdata.getProjectname();
		String projectintro = reqdata.getProjectintro();
		String invoiceContent = reqdata.getInvoiceContent();

		if (projectid <= 0 || StringUtil.isAnyEmpty(projectintro, projectname)) {
			return errorParamSmartResult();
		}
		CompanyProject project = new CompanyProject().selectById(projectid);
		Asserts.notNull(project, StatusMsg.StatusMsg_301);

		project.setProjectid(projectid).setProjectname(projectname).setProjectintro(projectintro).setInvoicecontent(invoiceContent);
		//普通项目的名称和发票内容改变后 发票表中的对应的数据也跟着改变
		Invoice invoice = new Invoice().selectOne(Condition.create().eq("projectid", projectid));
		if (null != invoice) {
			invoice.setProjectname(projectname).setContent(invoiceContent).updateById();
		}
		if (project.updateById()) {
			return smartResult();
		}
		return optFailSmartResult();
	}

	/**
	 * 仲裁项目金额
	 */
	public SmartResult arbitrateProject(BaseSimpleFormBean<ArbitrateFormBean> formBean) {

		ArbitrateFormBean reqdata = formBean.getReqdata();
		if (reqdata == null || reqdata.getAmount() == null || reqdata.getProjectid() <= 0 || reqdata.getAmount().doubleValue() < 0) {
			return errorParamSmartResult();
		}

		int projectid = reqdata.getProjectid();
		BigDecimal amount = reqdata.getAmount();
		String remark = reqdata.getRemark();

		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);

		if (amount.compareTo(project.getProjectamount()) > 0) {
			//仲裁金额不能大于项目原价
			return smartResult(StatusMsg.StatusMsg_318);
		}

		int newState;
		boolean allRefund = amount.doubleValue() == 0;
		if (allRefund) {
			//仲裁金额为0，将项目置为已仲裁已完成，项目款退回到企业账户
			newState = CompanyProjectState.COMPLETED;
		} else {
			newState = CompanyProjectState.CHECKED;
		}

		boolean update = project.setProjectdealamount(amount)
				.setState(newState)
				.setArbitrate(Constants.arbitratetstate_3)
				.setArbitrateRemark(remark)
				.updateById();

		if (update) {

			//将订单状态置为已退款,退款金额为 项目原价-仲裁金额
			BigDecimal refundamount = project.getProjectamount().subtract(amount);
			CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(project.getCompid(),project.getPayId());
			//记录上次余额
			BigDecimal beforeBalance = companyPayment.getBalance();
			//修改企业余额
			companyPayment.setBalance(companyPayment.getBalance().add(refundamount));
			int result = companyPaymentMapper.updateById(companyPayment);
			//记录更改后余额
			BigDecimal currBalance = companyPayment.getBalance();
			//生成企业流水账目
			boolean projectInsert = new CompanyAccountflow().setFlowAmount(refundamount)
					.setBeforeBalance(beforeBalance)
					.setCurrBalance(currBalance)
					.setBeforeFrozenBalance(companyPayment.getFrozenBalance())
					.setCurrFrozenBalance(companyPayment.getFrozenBalance())
					.setFlowname(project.getProjectname() + "项目仲裁退款")
					.setFlowtype(1)
					.setBizid(projectid)
					.setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
					.setCompid(project.getCompid())
					.setPayId(project.getPayId())
					.insert();
			if (result > 0 && projectInsert) {
				if (!allRefund) {//仲裁金额不等于0，走正常支付流程
					//正常的支付流程
					SmartResult smartResult = zhiduoduoProjectService.handleProjectPayment(project);
				}
				//通知创客及企业仲裁结果
				wxMessageService.notifyUserCompanyProjectArbitrate(projectid);
				return smartResult();
			}

		}
		//失败，回滚
		throw new RollbackException("仲裁失败");
	}

	/**
	 * @param tradeid
	 */
	public void queryTradeState(int tradeid) {
		LogUtil.info("查询交易支付: tradeid = " + tradeid);

		TradeRecord trade = new TradeRecord().selectById(tradeid);
		Integer payId = trade.getPayId();
		Payment payment = new Payment().selectById(payId);
		if(payment == null){
			LogUtil.info("交易支付处理：支付方式错误: tradeid = " + tradeid);
		}
		if(payment.getSourceTable() == 1) {
			// 招商银行支付方式
			if (PayTypeSn.ZS.equals(payment.getPayTypeSn())) {
				queryZhaoShangPayTradeState(trade);
			}
			//2023-04-23 新增平安支付方式
			else if (PayTypeSn.PA.equals(payment.getPayTypeSn())) {
				queryPinganPayTradeState(trade);
			}
		}
		//2022-12-11 新增支付宝支付方式
		else if (payment.getSourceTable() == 2) {
			aliPayTransferService.queryTradeResult(trade);
		}
	}

//	private void queryKltPayTradeState(TradeRecord trade) {
//		BaseSimpleFormBean<Object> formBean = new BaseSimpleFormBean<>();
//		formBean.setReqdata(trade.getTradeid());
//		RestTemplate rest = new RestTemplate();
//		SmartResult smartResult = rest.postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getQuerySinglePayUrl(), formBean,
//				SmartResult.class);
//		if (smartResult.getObject() != null && smartResult.isSuccessful()) {
//			QueryResultDto resultDto = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), QueryResultDto.class);
//
//			if (trade.getBusinessType() == Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
//				kltPayService.handlePayUserTradeState(trade, resultDto.getOrderState(), resultDto.getErrorCode(), resultDto.getErrorMsg());
//			else if (trade.getBusinessType() == Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
//				kltPayService.handlePayJiugeTradeState(trade, resultDto.getOrderState(), resultDto.getErrorCode(),
//						resultDto.getErrorMsg());
//		}
//	}

//	public void queryDaysPayTradeState(TradeRecord trade) {
//
//		DaysQueryAgentPayFormBean formBean = DaysQueryAgentPayFormBean.of(trade);
//		SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getDaysQueryAgentPayUrl(),
//				formBean, SmartResult.class);
//		if (smartResult.getObject() != null && smartResult.isSuccessful()) {
//			DaysQueryPayResDTO resultDto = JSON.parseObject(JSON.toJSONString(smartResult.getObject()), DaysQueryPayResDTO.class);
//
//			if (trade.getBusinessType() == Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
//				daysPayService.handlePayUserTradeState(trade, resultDto.getOrderState(), resultDto.getResponseCode(),
//						resultDto.getResponseRemark());
//			else if (trade.getBusinessType() == Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
//				daysPayService.handlePayJiugeTradeState(trade, resultDto.getOrderState(), resultDto.getResponseCode(),
//						resultDto.getResponseRemark());
//		}
//	}
//
//	public void queryTransferPayTradeState(TradeRecord trade) {
//
//		TransferQueryAgentPayFormBean formBean = TransferQueryAgentPayFormBean.of(trade.getPayAccount(), trade.getTradeno());
//		SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getTransferQueryAgentPayUrl(),
//				formBean, SmartResult.class);
//		if (smartResult.getObject() != null && smartResult.isSuccessful()) {
//			BaseResDTO<TransferQueryAgentPayResDTO> payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
//					new TypeReference<BaseResDTO<TransferQueryAgentPayResDTO>>() {
//					});
//			TransferQueryAgentPayResDTO resData = payResult.getData();
//			if ("success".equals(payResult.getResult()) && resData != null) {
//				trade.setPartnerOrderNo(resData.getBusinessrecordnumber());
//				transferPayService.handlePayUserTradeState(trade, resData.getStatus(), payResult.getCode(), payResult.getMsg());
//			} else {
//				transferPayService.handlePayUserTradeState(trade, "", payResult.getCode(), payResult.getMsg());
//			}
//		}
//	}

	public void queryZhaoShangPayTradeState(TradeRecord trade) {
		// 错误信息
		String errormsg = "";
		// 查询交易概要
		ZhaoShangTransactionOutlineFormBean outFormBean = ZhaoShangTransactionOutlineFormBean.of(trade.getMerchantid(), DateUtil.DateToStr("yyyyMMdd",trade.getTradetime()),trade.getTradeno());
		SmartResult smartResultOut = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryOutlineUrl(),
				outFormBean, SmartResult.class);
		if(smartResultOut.getObject() != null && smartResultOut.isSuccessful()){
			ZhaoShangOutlineDTO payResult = JSON.parseObject(JSON.toJSONString(smartResultOut.getObject()), new TypeReference<ZhaoShangOutlineDTO>() {});
			if ("F".equals(payResult.getRtnflg()) && StringUtil.isNotEmpty(payResult.getErrdsp())) {
				errormsg = payResult.getErrdsp();
			}
		}

		// 查询交易详情
		ZhaoShangQueryPayDetailedFormBean formBean = ZhaoShangQueryPayDetailedFormBean.of(trade.getMerchantid(),
				trade.getPartnerOrderNo());
		SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryAgentPayUrl(),
				formBean, SmartResult.class);
		if (smartResult.getObject() != null && smartResult.isSuccessful()) {
			ZhaoShangPayDetailedDTO payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
					new TypeReference<ZhaoShangPayDetailedDTO>() {
					});
			if (StringUtil.isNotEmpty(payResult.getErrtxt())) {
				errormsg = errormsg + payResult.getErrtxt();
			} else if (StringUtil.isNotEmpty(payResult.getErrdsp())) {
				errormsg = errormsg + payResult.getErrdsp();
			}
			zhaoShangPayService.handleZhaoShangPayUserTradeState(trade, payResult.getStscod(), payResult.getErrcod(), errormsg);
		}
	}
	public void queryPinganPayTradeState(TradeRecord trade) {
        PinganTransferQueryFormBean formBean = PinganTransferQueryFormBean.of(trade);
        SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getPinganSingleTransferQueryUrl(),
                formBean, SmartResult.class);
        pinganPayService.handleUserTradeState(trade, smartResult);
    }

	public void checkCrowdsourceBatchTradeState(int batchId) {
		log.info("查询智众包批量支付结果查询,batchId = {}", batchId);
		CrowdsourceTradeRecord tradeRecord = new CrowdsourceTradeRecord().selectById(batchId);
		if (tradeRecord == null) return;

		Integer payId = tradeRecord.getPayId();
		Payment payment = new Payment().selectById(payId);
		if(payment == null){
			log.info("查询智众包批量支付结果查询失败, 项目ID:{},支付方式不存在: {}", tradeRecord.getProjectid(),payId);
			return;
		}
		if (PayTypeSn.BTL.equals(payment.getPayTypeSn())) {
			log.info("智众包批量支付失败, 项目ID:{},支付方式为线下支付，不予处理！", tradeRecord.getProjectid());
			return;
		} else if (PayTypeSn.PA.equals(payment.getPayTypeSn())){
			PinganTransferQueryFormBean formBean = new PinganTransferQueryFormBean();
			formBean.setPaymentMerchant(tradeRecord.getMerchantid());
			formBean.setThirdVoucher(tradeRecord.getBatchNo());
			formBean.setTradeNo(tradeRecord.getBatchNo());
			RestTemplate rest = new RestTemplate();
			SmartResult smartResult = rest.postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getPinganBatchTransferQueryUrl(), formBean,
					SmartResult.class);
			if (smartResult.getObject() != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
				BatchTransferQuery resultDto = JSON.parseObject((String)smartResult.getObject(), BatchTransferQuery.class);
				crowdsourceProjectService.handleCrowdsourceProjectTradeQueryResultForPingan(resultDto, tradeRecord.getBatchNo());
			}

		} else {
			crowdsourceProjectService.queryCrowdsourceProjectTradeItemPayState(batchId);
		}
	}

	public void checkCrowdousrceTradeItemRepayState(int tradeRecordItemId) {

		log.info("查询智众包单笔明细重新支付结果, tradeRecordItemId = {}", tradeRecordItemId);

		CrowdsourceTradeRecordItem tradeItem = new CrowdsourceTradeRecordItem().selectById(tradeRecordItemId);
		CrowdsourceTradeRecord tradeRecord = new CrowdsourceTradeRecord().selectById(tradeItem.getBatchId());
		if (tradeItem == null) return;

		Integer payId = tradeRecord.getPayId();
		Payment payment = new Payment().selectById(payId);
		if (payment == null) {
			log.info("查询智众包单笔明细重新支付结果失败, 项目ID:{},支付方式ID不存在: {}", tradeRecord.getProjectid(), payId);
			return;
		}
		if (PayTypeSn.PA.equals(payment.getPayTypeSn())) {
			PinganTransferQueryFormBean formBean = PinganTransferQueryFormBean.of(tradeRecord.getMerchantid(),tradeItem.getTradeNo());
			SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getPinganSingleTransferQueryUrl(),
					formBean, SmartResult.class);
			LogUtil.info("查询单笔重新支付返回结果：" + JSON.toJSONString(smartResult));
			if (smartResult.getObject() != null && smartResult.getState() == StatusMsg.StatusMsg_100.getState()) {
				SingleTransferQuery transferQuery = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
						new TypeReference<SingleTransferQuery>() {
						});
				String orderState = "";
				String errormsg = "";
				if (PinganPayOrderState.SUCCESS.equals(transferQuery.getStt())) {
					orderState = "SUCCESS";
					errormsg = transferQuery.getBackRem();
				} else if (PinganPayOrderState.FAIL.equals(transferQuery.getStt())) {
					orderState = "FAIL";
					errormsg = transferQuery.getBackRem();
				} else {
					orderState = "IN_PROCESS";
				}
				crowdsourceProjectService.handleCrowdsourceProjectItemRepayTradeState(tradeItem, orderState,
						transferQuery.getStt(), errormsg);
			}
		}
	}

	public SmartResult calcProjectPartnerBrokerage(BaseSimpleFormBean<Integer> formBean) {

		Integer projectid = formBean.getReqdata();
		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);

		//代付给创客
		StudioDetailDto makerStudio = makerStudioMapper.getStudioDetail(project.getUserid());
		if (makerStudio == null) return smartResult(StatusMsg.StatusMsg_201);

		//项目服务费
		BigDecimal amount = project.getProjectamount();
		boolean isSpecialInvoice = NumberUtil.safeInt(project.getInvoicetype()) == 2;
		ProjectServiceChargeDto serviceCharge = coreProjectService.calcStudioServiceCharge(makerStudio, project.getCompid(), projectid,
				project.getType(), isSpecialInvoice, amount, CalcAmountType.ALL);

		List<PartnerProjectBrokerageDto> brokerageList = partnerBrokerageMapper.getZhiduoduoProjectBrokerageList(project.getProjectid(),
				ProjectType.ZHIDUODUO, 0).stream().map(partnerBrokerage -> {
			Double ratio = partnerBrokerage.getRatio();
			if (ratio == null) ratio = 0d;
			PartnerAccount partnerAccount = new PartnerAccount().selectOne(
					Condition.create().eq("partnerid", partnerBrokerage.getPartnerid()));

			BigDecimal brokerage = amount.multiply(BigDecimal.valueOf(ratio));

			PartnerProjectBrokerageDto dto = new PartnerProjectBrokerageDto();
			dto.setBrokerage(brokerage)
					.setPartnerid(partnerAccount.getPartnerid())
					.setPartnerName(partnerAccount.getRealname())
					.setRatio(ratio);

			return dto;
		}).collect(Collectors.toList());

		return smartResult(new ProjectServiceChargeCalcDto(projectid, serviceCharge.getServiceCharge(), brokerageList));
	}

	public SmartResult cancelProject(BaseSimpleFormBean<Integer> formBean) {
		Integer projectid = formBean.getReqdata();
		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) return smartResult(StatusMsg.StatusMsg_301);

		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(project.getCompid(),project.getPayId());
		if (companyPayment == null) return smartResult(StatusMsg.StatusMsg_330);

		// 是可以取消项目的几个状态
		if (CompanyProjectState.isCancelable(project.getState())) {

			BigDecimal projectAmount = project.getProjectamount();
			BigDecimal beforeBalance = companyPayment.getBalance();

			// 非线下项目，并且是需要退款的状态
			if(!PayTypeSn.BTL.equals(companyPayment.getPayTypeSn()) && CompanyProjectState.refundWhileCancelling(project.getState())){
				//企业账户余额增加退款金额
				BigDecimal currBalance = beforeBalance.add(projectAmount);
				companyPayment.setBalance(currBalance).updateById();

				//生成企业流水账目
				boolean companyFlow = new CompanyAccountflow().setFlowAmount(projectAmount)
															  .setPayId(companyPayment.getPayId())
															  .setBeforeBalance(beforeBalance)
															  .setCurrBalance(currBalance)
															  .setBeforeFrozenBalance(companyPayment.getFrozenBalance())
															  .setCurrFrozenBalance(companyPayment.getFrozenBalance())
															  .setFlowname(project.getProjectname() + "项目取消")
															  .setFlowtype(1)
															  .setBizid(projectid)
															  .setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
															  .setCompid(project.getCompid())
															  .insert();
				if (!companyFlow) SmartException.throwOf(StatusMsg.StatusMsg_199);
			}
			// 通用项目修改状态
			if (!project.setState(CompanyProjectState.CANCELLED).updateById()) {
				SmartException.throwOf(StatusMsg.StatusMsg_199);
			}
			// 删除佣金记录
			if (!new PartnerBrokerage().delete(Condition.create().eq("projectid", projectid))) {
				SmartException.throwOf(StatusMsg.StatusMsg_199);
			}

			zhiduoduoProjectService.doAfterProjectDeletedOrCancelled(project);
			return smartResult();
		}

		//不能取消
		return smartResult(StatusMsg.StatusMsg_305);
	}

	/**
	 * 作废项目 作废时判断发票状态，发票必须是作废状态项目才能作废，否则提示：请先将发票作废
	 * @param formBean
	 * @return
	 */
	public SmartResult uselessProject(BaseSimpleFormBean<UselessProjectFormBean> formBean) {
		UselessProjectFormBean reqdata = formBean.getReqdata();
		CompanyProject project = new CompanyProject().selectById(reqdata.getProjectId());
		Asserts.notNull(project, StatusMsg.StatusMsg_301);

		Invoice invoice = invoiceMapper.findByProjectid(project.getProjectid(), ProjectType.ZHIDUODUO);
		Asserts.notNull(invoice, StatusMsg.StatusMsg_326);
		if (Constants.invoicestate_6 != invoice.getState()) {
			return smartResult(StatusMsg.StatusMsg_379);
		}
		project.setState(CompanyProjectState.USELESS)
			   .setUselessReason(reqdata.getUselessReason())
			   .setUselessVoucher(reqdata.getUselessVoucher())
			   .updateById();
		//不能取消
		return smartResult();
	}

	/**
	 * 超过规定时间，自动验收项目
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public void autoCheckProject() {

		projectMapper.getAutoCheckProjectids(commonConfig.getAutoCheckProjectDays()).stream().map(id -> {

			LogUtil.info("自动验收项目projectid = " + id);
			ProjectCheckFormBean reqdata = new ProjectCheckFormBean();
			reqdata.setProjectid(id);
			reqdata.setState(CompanyProjectState.CHECKED);

			return reqdata;
		}).forEach(reqdata -> {
			try {
				//这里验收，可能会抛出回滚异常，直接捕捉，不处理。因为事务已经在CoreProjectService里面回滚了。
				zhiduoduoProjectService.checkProject(reqdata);
			} catch (Exception ignored) {}
		});
	}

	public void downloadProjectList(HttpServletResponse response, ProjectListFormBean reqdata) {

		String name = reqdata.getName();
		int state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		Date projectStartDate = reqdata.getProjectStartDate();
		Date projectEndDate = reqdata.getProjectEndDate();
		int categoryid = reqdata.getCategoryid();
		int whetherSupplement = reqdata.getWhetherSupplement();
		int whetherUploadFile = reqdata.getWhetherUploadFile();
		String strUploadFile = "";
		//1 已上传证据链  2  未上传证据链
		if (1 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url != '' and cp.attachment_url is not null) or cp.delivery_path is not null) ";
		} else if (2 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url is null or cp.attachment_url = '') and cp.delivery_path is null) ";
		}
			List<ProjectBriefDto> list = projectMapper.getProjectBriefList(name, categoryid, state, startDate, endDate, strUploadFile,
					whetherSupplement, projectStartDate, projectEndDate,null,0);

		String file = "项目列表";
		try {
			if (reqdata.getAuth() == 1) {
				EasyExcel.write(getExcelOutPutStream(response, file), ProjectBriefDto.class).sheet(file).doWrite(list);
			} else {
				EasyExcel.write(getExcelOutPutStream(response, file), ProjectBriefsDto.class).sheet(file).doWrite(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SmartResult projectJiugeOfflinePayFinish(BaseSimpleFormBean<ProjectJiugeOfflinePayFinishFormBean> formBean) {
		@Valid ProjectJiugeOfflinePayFinishFormBean reqdata = formBean.getReqdata();
		int projectid = reqdata.getProjectid();
		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) return SmartResult.fail(StatusMsg.StatusMsg_301);
		if (project.getPayId() != CompanyPayType.PLATFORM_OFFLINE) {
			return SmartResult.fail(StatusMsg.StatusMsg_456);
		}
		if (project.getOfflinePayState() != Constants.OFFLINE_PAYING) {
			return SmartResult.fail(StatusMsg.StatusMsg_449);
		}

		// 处理九歌线下支付成功
		project.setReceiptimg(reqdata.getReceiptImg())
				.setRemark(reqdata.getRemark())
				.setOfflinePayAdminid(formBean.getUserid())
				.setOfflinePayTime(new Date())
				.setOfflinePayState(Constants.OFFLINE_PAID);
		// 更新银行卡开户网点
		makerBankcardMapper.updateOpenAcctBankName(reqdata.getOpenAcctBankName(), project.getUserid());
		zhiduoduoProjectService.getProjectPaymentService(project).doAfterPayUserTradeSucceed(project, null);

		return SmartResult.success();
	}

	public SmartResult importDealedProject(MultipartFile file, int userid,int payId, int whetherJiYong) {
		if (0 == userid || 0 == payId) {
			return errorParamSmartResult();
		}
		if(file == null || file.isEmpty()){
			return smartResult(StatusMsg.StatusMsg_134);
		}
		try {
			//读取文件
			UploadDealProjectListener listener = new UploadDealProjectListener(userid,payId, whetherJiYong, companyMapper, coreCompanyService, coreInvoiceService,coreBrokerageService);
			EasyExcel.read(file.getInputStream(), ImportZddProjectTemplateFormBean.class, listener).sheet().doRead();
			return listener.getSmartResult();
		} catch (Exception e) {
			log.error("importDealedProject 导入 补录文件解析失败：{}", e.getMessage());
			//手动回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return SmartResult.fail(StatusMsg.StatusMsg_135, e.getMessage());
		}
	}

	public SmartResult deleteImportDealedProject(BaseSimpleFormBean<Object[]> formBean) {
		if (formBean == null || formBean.getReqdata() == null) {
			return errorParamSmartResult();
		}
		Object[] projectIds = formBean.getReqdata();
		if (projectIds.length == 0) {
			return smartResult("请选择要删除的数据");
		}
		List<CompanyProject> companyProjects = new CompanyProject().selectList(Condition.create().in("projectid", projectIds));

		if (companyProjects.size() == 0) {
			return smartResult(StatusMsg.StatusMsg_301);
		}

		for (CompanyProject companyProject : companyProjects) {
			if (!companyProject.deleteById()) {
				return smartResult(StatusMsg.StatusMsg_199);
			}

			//加回企业余额
			CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(companyProject.getCompid(), companyProject.getPayId());
			if (companyPayment == null) {
				return smartResult(StatusMsg.StatusMsg_330);
			}

			BigDecimal projectAmount = companyProject.getProjectamount();
			BigDecimal beforeBalance = companyPayment.getBalance();
			//企业账户余额增加退款金额
			BigDecimal currBalance = beforeBalance.add(projectAmount);
			companyPayment.setBalance(currBalance).updateById();
			//生成企业流水账目
			boolean companyFlow = new CompanyAccountflow()
					.setFlowAmount(projectAmount)
					.setPayId(companyPayment.getPayId())
					.setBeforeBalance(beforeBalance)
					.setCurrBalance(currBalance)
					.setBeforeFrozenBalance(companyPayment.getFrozenBalance())
					.setCurrFrozenBalance(companyPayment.getFrozenBalance())
					.setFlowname(companyProject.getProjectname() + "项目取消").setFlowtype(1)
					.setBizid(companyProject.getProjectid())
					.setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
					.setCompid(companyProject.getCompid())
					.setPayId(companyProject.getPayId())
					.insert();
			if (!companyFlow) {
				return smartResult(StatusMsg.StatusMsg_199);
			}

			Invoice invoice = new Invoice().selectOne(Condition.create().eq("projectid", companyProject.getProjectid()));
			if (invoice != null && !invoice.deleteById()) {
				return smartResult(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();

	}

	/**
	 * 上传 项目证据链
	 *
	 * @param formBean formBean
	 * @return success
	 */
	@Transactional
	public SmartResult uploadProjectFileUrl(BaseSimpleFormBean<UploadProjectFileUrlFormBean> formBean) {
		if (null == formBean || null == formBean.getReqdata() || CollectionUtils.isEmpty(formBean.getReqdata().getProjectIds())) {
			return errorParamSmartResult();
		}
		UploadProjectFileUrlFormBean reqdata = formBean.getReqdata();
		// 项目信息
		List<CompanyProject> companyProjectList = new CompanyProject().selectList(
				Condition.create().in("projectid", reqdata.getProjectIds()));
		if (CollectionUtils.isEmpty(companyProjectList)) {
			return smartResult(StatusMsg.StatusMsg_301);
		}
		for (CompanyProject companyProject : companyProjectList) {
			companyProject.setAttachmentUrl(reqdata.getProjectFileUrl());
			//保存备注
			companyProject.setRemarksField(reqdata.getRemarksField());
			if (!companyProject.updateById()) {
				throw new SmartException(StatusMsg.StatusMsg_199);
			}
		}
		return smartResult();
	}

	/**
	 * 针对已验收的项目生成为交付物
	 *
	 * @param formBean
	 * @return
	 */
	public SmartResult generateProjectDeliveryFile(BaseSimpleFormBean<GenerateProjectAcceptance> formBean) {
		GenerateProjectAcceptance acceptance = formBean.getReqdata();
		Asserts.notEmpty(acceptance.getProjectIds(), StatusMsg.StatusMsg_136);

		List<ExportProjectAcceptanceDto> dtos = docService.generatezddProjectDocDeliverFile(0, acceptance.getProjectIds());
		Set<String> projectIds = dtos.stream().map(t -> t.getProjectid().toString()).collect(Collectors.toSet());

		if (org.apache.commons.lang.StringUtils.isNotBlank(acceptance.getProjectIds())) {
			if (CollectionUtils.isEmpty(dtos)) {
				return SmartResult.fail(StatusMsg.StatusMsg_142);
			}
			String[] originalIds = acceptance.getProjectIds().split(",");
			if (projectIds.size() != originalIds.length) {
				Set<String> originalList = new HashSet<>(Arrays.asList(originalIds));
				originalList.removeAll(projectIds);
				return SmartResult.success(originalList);
			}
		}
		return SmartResult.success();
	}

	/**
	 * 下载项目生成交付压缩文件
	 *
	 * @param response
	 * @param compid
	 * @param projectType
	 * @param projectIdList
	 */
	public void downloadProjectDeliveryZipFile(HttpServletResponse response, int compid, int projectType, int templateType,
	                                           List<Integer> projectIdList) {
		if (projectIdList == null || projectIdList.size() <= 0) return;

		if (projectType == ProjectType.ZHIDUODUO) {
			List<ExportProjectAcceptanceDto> list = docService.generatezddProjectDocDeliverFile(compid,
					org.apache.commons.lang3.StringUtils.join(projectIdList, ","));
			docService.downloadDeliveryProjectDoc(response, list);
		} else {
			Asserts.isTrue(NumberUtil.intIn(templateType, 2, 3));
			List<ExportProjectAcceptanceDto> list = docService.generateCrowdsourceDocDeliverFile(compid,
					org.apache.commons.lang3.StringUtils.join(projectIdList, ","), templateType, false);
			docService.downloadDeliveryProjectDoc(response, list);
		}
	}

	public void refreshMakerBidProjectDate() {
		// 竞标结束日期小于当前指定日期DateUtil.nowDate()，修改为竞标结束状态
		projectMapper.updateOpenBidEnd(DateUtil.nowDate(), CompanyProjectState.BID_FINISH);

	}

	/**
	 * 获取项目列表数量
	 */
	public int getProjectListQuantity(ProjectListFormBean reqdata) {
		String name = reqdata.getName();
		int state = reqdata.getState();
		Date startDate = reqdata.getStartDate();
		Date endDate = reqdata.getEndDate();
		int categoryid = reqdata.getCategoryid();
		Date projectStartDate = reqdata.getProjectStartDate();
		Date projectEndDate = reqdata.getProjectEndDate();

		int whetherUploadFile = reqdata.getWhetherUploadFile();
		String strUploadFile = "";
		//1 已上传证据链  2  未上传证据链
		if (1 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url != '' and cp.attachment_url is not null) or cp.delivery_path is not null) ";
		} else if (2 == whetherUploadFile) {
			strUploadFile = " and ((cp.attachment_url is null or cp.attachment_url = '') and cp.delivery_path is null) ";
		}
		int whetherSupplement = reqdata.getWhetherSupplement();
		List<ProjectBriefDto> list = projectMapper.getProjectBriefList(name, categoryid, state, startDate, endDate, strUploadFile,
				whetherSupplement, projectStartDate, projectEndDate,null,0);
		return list.size();
	}

	public SmartResult getMakerAllProjectList(BaseSimpleFormBean<QueryMakerAllProjectFormBean> formBean){
		QueryMakerAllProjectFormBean req = formBean.getReqdata();
		Page<MakerAllProjectDto> page = PageHelper.startPage(formBean.getPage(),formBean.getRows());
		List<MakerAllProjectDto> list = projectMapper.getMakerAllProject(req.getRealname(),req.getUsername(),req.getIdno(),
				req.getProjectTypes(),req.getPublishStart(),req.getPublishEnd());
		return smartResultPage(page);
	}

	public void exportMakerAllProjectList(HttpServletResponse response, QueryMakerAllProjectFormBean req){
		List<MakerAllProjectDto> list = projectMapper.getMakerAllProject(req.getRealname(),req.getUsername(),req.getIdno(),
				req.getProjectTypes(),req.getPublishStart(),req.getPublishEnd());

		String file = RandomUtil.createRandomNo("同一用户所有交易数据", "");
		try {
			EasyExcel.write(getExcelOutPutStream(response, file), MakerAllProjectDto.class).sheet("同一用户所有交易数据").doWrite(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询众包招商银行交易成功的交易后续是否存在退票，如果退票修改项目状态，发送通知
	 */
	public void queryZhaoShangPayTradeIsFail(){
		tradeRecordMapper.getSuccessTradeIds().forEach(trade -> {
			try {
				ZhaoShangQueryPayDetailedFormBean formBean = ZhaoShangQueryPayDetailedFormBean.of(trade.getMerchantid(),
						trade.getPartnerOrderNo());
				SmartResult smartResult = new RestTemplate().postForObject(zddUrlConfig.getBasePayUrl() + payConfig.getZhaoShangQueryAgentPayUrl(),
						formBean, SmartResult.class);
				if (smartResult.getObject() != null && smartResult.isSuccessful()) {
					ZhaoShangPayDetailedDTO payResult = JSON.parseObject(JSON.toJSONString(smartResult.getObject()),
							new TypeReference<ZhaoShangPayDetailedDTO>() {
							});
					String errormsg = "";
					if (StringUtil.isNotEmpty(payResult.getErrtxt())) {
						errormsg = payResult.getErrtxt();
					} else {
						errormsg = payResult.getErrdsp();
					}
					if (ZhaoShangPayOrderState.FAIL.equals(payResult.getStscod())) {
						trade.setErrorcode(payResult.getErrcod())
								.setErrormsg(errormsg)
								.setTradestate(Constants.TRADE_FAIL)
								.setFinishtime(new Date())
								.updateById();
						// 修改项目状态
						CompanyProject project = new CompanyProject().selectById(trade.getProjectid());
						if (project != null) {
							project.setState(CompanyProjectState.CANCELLED).updateById();
						}
						// 发送通知
						wxMessageService.notifyAdminPaymentFail(trade);
					}
				}
			} catch (Exception e) {
				log.error("queryZhaoShangPayTradeIsFail exception:", e);
			}
		});
	}
	public SmartResult projectRefunds(@RequestBody BaseSimpleFormBean<CompanyProject> formBean) {
		CompanyProject companyProject = projectMapper.selectById(formBean.getReqdata().getProjectid());
		if (null == companyProject){
			return smartResult(StatusMsg.StatusMsg_102);
		}
		projectMapper.updateById(
				companyProject
						.setAmountOfRefund(formBean.getReqdata().getAmountOfRefund())
						.setRefundTime(formBean.getReqdata().getRefundTime())
						.setRefundVoucher(formBean.getReqdata().getRefundVoucher())
						.setRefundRecordPersonId(formBean.getUserid())
						.setWhetherThereIsARefund(1)
						.setReasonForRefund(formBean.getReqdata().getReasonForRefund()));
		return smartResult();
	}
}
